package com.engine4cloud.tdf.supervision.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.engine4cloud.tdf.common.data.web.query.Queries;
import com.engine4cloud.tdf.common.security.service.TdfUser;
import com.engine4cloud.tdf.common.security.util.SecurityUtils;
import com.engine4cloud.tdf.supervision.convert.JzdxIdentityCardConvert;
import com.engine4cloud.tdf.supervision.dto.create.TerminalIdentityCardCreateDTO;
import com.engine4cloud.tdf.supervision.dto.update.TerminalIdentityCardUpdateDTO;
import com.engine4cloud.tdf.supervision.entity.JzdxIdentityCardEntity;
import com.engine4cloud.tdf.supervision.mapper.JzdxIdentityCardMapper;
import com.engine4cloud.tdf.supervision.service.JzdxIdentityCardService;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 矫正对象身份证信息
 *
 * @author wenjie
 * @date 2024-07-19 17:22:24
 */
@Service
public class JzdxIdentityCardServiceImpl extends ServiceImpl<JzdxIdentityCardMapper, JzdxIdentityCardEntity> implements JzdxIdentityCardService {
    @Override
    public JzdxIdentityCardEntity findOne(String identity) {
        return super.getOne(wrapper(identity));
    }

    @Override
    public Boolean create(TerminalIdentityCardCreateDTO dto) {
        JzdxIdentityCardEntity identity = this.findOne(dto.getIdentity());
        if (Objects.nonNull(identity)) {
            return super.updateById(JzdxIdentityCardConvert.INSTANCE.update(dto, identity.getId()));
        }

        TdfUser user = SecurityUtils.getUser();
        return super.save(JzdxIdentityCardConvert.INSTANCE.create(dto, user.getTenantId()));
    }

    @Override
    public Boolean update(TerminalIdentityCardUpdateDTO dto) {
        if (Objects.nonNull(dto.getId())) {
            return super.updateById(JzdxIdentityCardConvert.INSTANCE.update(dto, dto.getId()));
        }

        TdfUser user = SecurityUtils.getUser();
        return super.save(JzdxIdentityCardConvert.INSTANCE.create(dto, user.getTenantId()));
    }

    private LambdaQueryWrapper<JzdxIdentityCardEntity> wrapper(String identity) {
        LambdaQueryWrapper<JzdxIdentityCardEntity> wrapper = Queries.lambda();
        Queries.accept(identity, v -> wrapper.eq(JzdxIdentityCardEntity::getIdentity, v));
        return wrapper;
    }

}